<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *费用表
 */
class Consume Extends Model {
	use SoftDelete;

    // 表名,不含前缀
    const   CONTRACT_TYPE = 'contract';
    const   RECEIVABLES_TYPE = 'receivables';//订单
    const   CUSTOMER_TYPE = 'customer';//回款
    const   WORKORDER_TYPE = 'workorder';//报价单
    const   EVENT_TYPE = 'event';//工单
    // 表名,不含前缀
    protected $name = 'qingdongams_consume';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


    // 追加属性
    protected $append = [
        'file_text',
        'relation_data',
        'title_text',
    ];

    public static function getconsumetype() {
        return [
            'jtf'   =>  '交通费',
            'clf'   =>  '差旅费',
            'call'   =>  '电话费',
            'jjf'   =>  '交际费',
            'bgkx' =>  '办公开销',
            'cgf'   =>  '采购费',
            'ggf'   =>  '广告宣传费',
            'other' =>  '其他费用',
        ];
    }
    public static function getNumber()
    {
        return 'M' . date('ymd') . rand(100, 999);
    }
    public function getTitleTextAttr($value, $data)
    {
        $value = $value ? $value : '';
        if (isset($value) && $value) {
            return $value;
        } else {
            return '日常报销';
        }
    }

    public function getRelationDataAttr($value, $data)
    {
        if (!isset($data['relation_type'])) {
            return '';
        }
        if ($data['relation_type'] == self::WORKORDER_TYPE) {
            return Workorder::where(['id' => $data['relation_id']])->field('id,title,workorder_number')->find();
        } elseif ($data['relation_type'] == self::EVENT_TYPE) {
            return Event::where(['id' => $data['relation_id']])->field('id,title')->find();
        }
        return [];
    }
    //添加费用
    public function getCheckStatusTextAttr($value, $data)
    {
        $check_status=$data['check_status']??0;
        $a = [0 => __('待审核'), 1 => __('审核中'), 2 => __('审核通过'), 3 => __('审核未通过')];
        return $a[$check_status] ?? '';
    }


    // 图片
    public function getFileTextAttr($value, $data)
    {
        if(!isset($data['file_ids'])){
            return '';
        }
        if(is_array($value)){
            return $value;
        }
        $value = $value ? $value : $data['file_ids'];
        $files      = explode(',',$value);
        $files_v = [];
        foreach ($files as $fid) {
            if($fid){
                $files_v[] = cdnurl(File::getUrl($fid), true);
            }
        }
        return $files_v;
    }

	//添加费用
	public static function createConsume($params) {
        foreach ($params as $name => $val) {
            if($params[$name] === ''){
                $params[$name]=NULL;
            }
        }

		$staff                  = Staff::info();
        $staff_id = $staff->id;
		if(isset($params['customer_id']) && $params['customer_id']){
            $staff_id = Customer::where(['id'=>$params['customer_id']])->value('owner_staff_id');
        }
		$params['staff_id']     = $staff_id;
		$params['check_status'] = 1;
        $flow = Flow::getsteplist(Flow::CONSUME_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];
        $detailes = $params['detail']??[];
        unset($params['detail']);
        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
//                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']??'');
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }

        $Model                  = new self;
        $result = $Model->allowField(true)->save($params);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}
        $lastId= $Model->getLastInsID();
        $detail = [];
        foreach ($detailes as $v) {
            $detail[] = [
                'customer_id' => $params['customer_id']??0,
                'consume_id' => $lastId,
                'consume_date' => $v['consume_date'],
                'consume_type' => $v['consume_type'],
                'consume_money' => $v['consume_money'],
                'remark' => $v['remark'] ?? '',
                'file_ids' => $v['file_ids'] ?? '',
                'mileage' => $v['mileage'] ?? '',
                'car_number' => $v['car_number'] ?? '',
                'car_type' => $v['car_type'] ?? '',
                'start_mileage' => $v['start_mileage'] ?? '',
                'end_mileage' => $v['end_mileage'] ?? '',
                'other_files' => $v['other_files'] ?? '',
            ];
        }
        $detailModel = new ConsumeDetail();
        $detailModel->insertAll($detail);

		$staff_id = explode(',', $params['flow_staff_ids'])[0];

		ExamineRecord::addExaminse(ExamineRecord::CONSUME_TYPE,$lastId, $staff_id);

		return true;
	}


	//编辑费用
	public static function updateConsume($params) {
		$params['check_status'] = 1;

        $flow = Flow::getsteplist(Flow::CONSUME_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }
        $detailes = $params['detail']??[];
        unset($params['detail']);

		$Model                  = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $Model->save($params,['id'=>$params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}
        $detail = [];
        foreach ($detailes as $v) {
            $detail[] = [
                'customer_id' => $params['customer_id']?:0,
                'consume_id' => $params['id'],
                'consume_date' => $v['consume_date'],
                'consume_type' => $v['consume_type'],
                'consume_money' => $v['consume_money'],
                'remark' => $v['remark'] ?? '',
                'file_ids' => $v['file_ids'] ?? '',
                'mileage' => $v['mileage'] ?? '',
                'car_number' => $v['car_number'] ?? '',
                'car_type' => $v['car_type'] ?? '',
                'start_mileage' => $v['start_mileage'] ?? '',
                'end_mileage' => $v['end_mileage'] ?? '',
                'other_files' => $v['other_files'] ?? '',
            ];
        }   
        $detailModel = new ConsumeDetail();
        $detailModel->where(['consume_id'=>$params['id']])->delete();
        $detailModel->insertAll($detail);

        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::CONSUME_STATUS, $params['id']);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::CONSUME_TYPE, $params['id'], $staff_id);
            }
        }

		return true;
	}
    //计算交通费
    public static function getMileageMoney($number)
    {
        return $number * 10;
    }

    public function getCreatetimeAttr($value){
        if(empty($value)){
            return $value;
        }
        return date('Y-m-d H:i:s',$value);
    }
    public function getUpdatetimeAttr($value){
        if(empty($value)){
            return $value;
        }
        return date('Y-m-d H:i:s',$value);
    }

	//销售
	public function staff() {
		return $this->hasOne(Staff::class, 'id', 'staff_id')
            ->field('id,img,name,mobile');
	}

    //审核人
    public function followStaff() {
        return $this->hasOne(Staff::class, 'id', 'flow_staff_ids')
            ->field('id,img,name,mobile');
    }

	//客户
	public function customer() {
		return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name');
	}
    //费用详情
    public function consumeDetail()
    {
        return $this->hasMany(ConsumeDetail::class, 'consume_id', 'id');
    }

}
